package com.dragon8869.myspringboot.listener;

import com.dragon8869.myspringboot.entity.AyUser;
import com.dragon8869.myspringboot.service.AyUserService;
import com.dragon8869.myspringboot.service.MailService;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebListener
@Log4j2
public class AyUserListener implements ServletContextListener {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private AyUserService ayUserService;

    @Resource
    MailService mailService;

    private final static String ALL_USER_LIST = "all_user_list";



    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.trace("AyUserListener.contextInitialized");

        // 下面代码让spring注入ayUserService和redisTemplate
        // https://blog.csdn.net/snail_spoor/article/details/53426134
        WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext())
                .getAutowireCapableBeanFactory().autowireBean(this);

        /*WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
        ayUserService = context.getBean("ayUserService", AyUserService.class);
        redisTemplate = context.getBean(RedisTemplate.class);*/


        redisTemplate.delete(ALL_USER_LIST);

        List<AyUser> ayUsers = ayUserService.findAll();

        redisTemplate.opsForList().leftPushAll(ALL_USER_LIST, ayUsers.toArray());

        List<Object> list = redisTemplate.opsForList().range(ALL_USER_LIST, 0, -1);

        Assert.notNull(list, "list为空");

        System.out.println("缓存中的用户数:" + list.size());
        log.info("缓存中的用户数:" + list.size() + ", " + list);

        int index = ayUsers.size() - 1;
        while (index >= 0) {
            if (!StringUtils.hasLength(ayUsers.get(index).getEmail())){
                ayUsers.remove(index);
            }
            index--;
        }
        try {
            mailService.sendMail(ayUsers);
            log.info("邮件发送成功");
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("邮件发送成功", e);
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.trace("AyUserListener.contextDestroyed");

        ayUserService = null;
        redisTemplate = null;
    }
}
